package com.lk.springboot.controller;

import java.util.List;

import com.lk.springboot.bean.Press;
import com.lk.springboot.dao.CategoryMapper;
import com.lk.springboot.bean.Category;
import com.lk.springboot.dao.PressMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

@Controller
public class CategoryController {
    @Autowired
    CategoryMapper categoryMapper;


    @RequestMapping("/addCategory")
    public String listCategory(Category c) throws Exception {
        categoryMapper.save(c);
        return "redirect:listCategory";
    }

    @RequestMapping("/deleteCategory")
    public String deleteCategory(Category c) throws Exception {
        categoryMapper.delete(c.getB_id());
        return "redirect:listCategory";
    }

    @RequestMapping("/updateCategory")
    public String updateCategory(Category c) throws Exception {
        categoryMapper.update(c);
        return "redirect:listCategory";
    }

    @RequestMapping("/editCategory")
    public String listCategory(int id, Model m) throws Exception {
        Category c = categoryMapper.get(id);
        m.addAttribute("c", c);
        return "editCategory";
    }

    @RequestMapping("/listCategory")
    public String listCategory(Model m, @RequestParam(value = "start", defaultValue = "0") int start, @RequestParam(value = "size", defaultValue = "15") int size) throws Exception {
        PageHelper.startPage(start, size, "b_id asc");
        List<Category> cs = categoryMapper.findAll();
        PageInfo<Category> page = new PageInfo<>(cs);
        m.addAttribute("page", page);
        return "listCategory";
    }

    @RequestMapping("/searchBook")
    public String searchList(Category c,Model m, @RequestParam(value = "start", defaultValue = "0") int start, @RequestParam(value = "size", defaultValue = "15") int size) throws Exception {
        PageHelper.startPage(start, size, "b_id asc");
        List<Category> cs = null;
        if (c.getAuthor() != "") {
            cs = categoryMapper.findByAuthor(c.getAuthor());
        } else if (c.getTitle() != ""){
            cs = categoryMapper.findByTitle(c.getTitle());
        }else if (c.getAuthor()== "" && c.getTitle() == ""){
            cs = categoryMapper.findAll();
        }
        PageInfo<Category> page = new PageInfo<>(cs);
        m.addAttribute("page", page);
        return "listCategory";
    }

    @RequestMapping("/editaddCategory")
    public String editaddCategory(Category c) throws Exception {
        return "editaddCategory";
    }

}